<?php

namespace app\modules\admin\controllers;

use app\common\controllers\CorsController;
use app\config\Constants;
use app\modules\admin\forms\LoginForm;
use yii\base\UserException;

class LoginController extends CorsController {

    public function actionIndex(){
        $form = new LoginForm();
        if($form->load(\Yii::$app->getRequest()->post(),'') && $form->login()){
            $expire = time() + \Yii::$app->params['token_expire'];
            return [
                'expire'=>$expire,
                'token'=>(string)\Yii::$app->jwt->getBuilder()
                    ->expiresAt($expire) //设置token过期时间
                    ->withClaim('uid', $form->getUser()->admin_id) //设置Payload数据
                    ->withClaim("credential",Constants::ADMIN)
                    ->getToken(\Yii::$app->jwt->getSigner("HS256"),\Yii::$app->jwt->getKey())
            ];
        }else{
            throw new UserException($form->getFirstFieldError());
        }
    }
}